import { ChartServiceBase } from '@/ibiz-core';
import { Util, HttpResponse } from '@/ibiz-core/utils';
import { TrendModel } from '@/app-core/ctrl-model/res-partner/trend-chart-model';


/**
 * Trend 部件服务对象
 *
 * @export
 * @class TrendService
 * @extends {ChartServiceBase}
 */
export class TrendService extends ChartServiceBase {

    /**
     * 部件模型
     *
     * @protected
     * @type {TrendModel}
     * @memberof ControlServiceBase
     */
    protected model: TrendModel = new TrendModel();

    /**
     * 应用实体名称
     *
     * @protected
     * @type {string}
     * @memberof TrendService
     */
    protected appDEName: string = 'res_partner';

    /**
     * 当前应用实体主键标识
     *
     * @protected
     * @type {string}
     * @memberof TrendService
     */
    protected appDeKey: string = 'id';

    /**
     * 生成图表数据
     *
     * @param {string} action
     * @param {*} response
     * @memberof TrendService
     */
    public handleResponse(action: string, response: any): any {
        const chartOption: any = {};
        const catalogFields: any = ["create_date",];
        const valueFields: any = [[ "id", "ID" ],];
        // 数据按分类属性分组处理
        const xFields:any = [];
        const yFields:any = [];
        valueFields.forEach((field: any, index: number) => {
            yFields[index] = [];
        });
        response.data.forEach((item:any) => {
            if(xFields.indexOf(item[catalogFields[0]]) > -1){
                const num = xFields.indexOf(item[catalogFields[0]]);
                valueFields.forEach((field: any,index: number) => {
                    yFields[index][num] += item[field[0]];
                });
            }else{
                xFields.push(item[catalogFields[0]]);
                valueFields.forEach((field: any,index: number) => {
                    yFields[index].push(item[field[0]]);
                });
            }
        });
        chartOption.xAxis = { data: xFields };
        const series: any = [];
        valueFields.forEach((field: any,index: number) => {
            const yData: any = [];
            xFields.forEach((item:any, num: number) => {
                yData.push(yFields[index][num]);
            });
            yData.sort(function (a:any, b:any) { return a.value - b.value; });
            series.push({
              name: field[1],
              type: "line",
              data: yData,
            });
        });
        chartOption.series = series;
        return new HttpResponse(response.status, chartOption);
    }

}
// 默认导出
export default TrendService;